<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com>
// +----------------------------------------------------------------------

namespace App\Models;

use Cache;

/**
 * 配置模型
 */
class Config extends BaseModel
{

    protected $table = "config";

    const DB_CONFIG_DATA = 'DB_CONFIG_DATA';

    /* 用户模型自动验证 */
    protected $rules = [
        /* 验证标识 */
        'name' => 'required|unique:config',
        /* 验证名称 */
        'title' => 'required|unique:config',
    ];

    protected $message = [
        /* 标识验证信息 */
        'name.required' => '标识不能为空',
        'name.unique' => '标识已经存在',
        /* 名称验证信息 */
        'title.required' => '标题不能为空',
        'title.unique' => '标题已经存在',
    ];


    /**
     * 获取配置列表
     * @return array 配置数组
     */
    public function getCache()
    {
        $config = Cache::get(self::DB_CONFIG_DATA);
        if (!$config) {
            $where['status'] = 1;
            $data = $this->_getList($where, 'type,name,value');
            if ($data) {
                $data = $data->toArray();
            }
            $config = [];
            if ($data && is_array($data)) {
                foreach ($data as $value) {
                    $config[$value['name']] = $this->parse($value['type'], $value['value']);
                }
            }
            Cache::forever(self::DB_CONFIG_DATA, $config);
        }
        return $config;
    }

    public function generate()
    {
        Cache::forget(self::DB_CONFIG_DATA);
        $config = $this->getCache();
        C($config);
    }

    /**
     * 根据配置类型解析配置
     * @param  integer $type 配置类型
     * @param  string $value 配置值
     */
    private function parse($type, $value)
    {
        switch ($type) {
            case 3: //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if (strpos($value, ':')) {
                    $value = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val);
                        $value[$k] = $v;
                    }
                } else {
                    $value = $array;
                }
                break;
        }
        return $value;
    }

    public function addOrUpdate()
    {
        $data['name'] = trim(request('name'));
        $data['title'] = trim(request('title'));
        if (request()->has('id')) {
            $data['id'] = trim(request('id'));
            $this->rules['name'] = $this->rules['name'] . ',id,' . $data['id'];
            $this->rules['title'] = $this->rules['title'] . ',id,' . $data['id'];
        }
        if (!$this->_validate($data)) {
            return false;
        }
        $data['remark'] = trim(request('remark'));
        $data['extra'] = trim(request('extra'));
        $data['value'] = trim(request('value'));
        $data['group'] = trim(request('group'));
        $data['type'] = trim(request('type'));
        $data['status'] = trim(request('status', 1));
        $data['sort'] = trim(request('sort'));
        $res = $this->_save($data);
        if ($res) {
            if (isset($data['id'])) {
                $actionLog = new ActionLog();
                $actionLog->action_log('update_config', 'config', $data['id'], session('admin.id'));
            }
            $this->generate();
        }
        return $res;
    }

    public function del()
    {
        $id = request('id');
        $id = is_array($id) ? $id : [$id];
        $id = array_unique($id);
        if (empty($id)) {
            $this->error = '请选择要操作的数据!';
            return false;
        }
        $where['id'] = ['in', $id];
        $res = $this->_del($where);
        if (!$res) {
            $this->error = '删除失败!';
            return false;
        }
        //记录行为
        $actionLog = new ActionLog();
        $actionLog->action_log('update_config', 'config', implode(',', $id), session('admin.id'));
        $this->generate();
        return '删除成功';
    }

}
